package com.zry.fertilizer.ui.fragment

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Intent
import android.os.Build
import android.util.Log
import android.view.View
import android.widget.ProgressBar
import android.widget.TextView
import com.tsy.sdk.myokhttp.response.DownloadResponseHandler
import com.zry.fertilizer.MainActivity
import com.zry.fertilizer.R
import com.zry.fertilizer.databinding.FragmentUserBinding
import com.zry.fertilizer.retrofit.BaseApiRetrofit
import com.zry.fertilizer.retrofit.HttpServer
import com.zry.fertilizer.retrofit.ShowUserView
import com.zry.fertilizer.ui.activity.LoginActivity
import com.zry.fertilizer.ui.base.BaseFragment
import com.zry.fertilizer.update.PackageInfoUtil
import com.zry.fertilizer.update.UpdateAppInfo
import com.zry.fertilizer.update.UpdateAppService
import com.zry.fertilizer.update.UpdateUtils
import com.zry.fertilizer.utils.ACacheUtil
import com.zry.fertilizer.utils.ToastUtil
import com.zry.fertilizer.view.DialogUtil
import kotlinx.android.synthetic.main.fragment_user.*
import java.io.File


class UserFragment : BaseFragment(), ShowUserView {
    private var userBinding: FragmentUserBinding? = null
    private var mainActivity: MainActivity? = null
    override fun setOnCreate() {
        mainActivity = activity as MainActivity
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_user
    }

    override fun initDataView() {
        userBinding = fragmentDataBinding as FragmentUserBinding
        userBinding?.moreClick = this

        userBinding?.userNameText?.text = ACacheUtil().getUsername()
        userBinding?.userAccountText?.text = ACacheUtil().getUsername()
        userBinding?.userUnit?.text = ACacheUtil().getLoginInfo().EntName

        checkApp(PackageInfoUtil.getVersionName(mainActivity!!).toString())
    }

    fun moreOperateClick(view: View) {
        when (view.id) {
            R.id.versionUpdateRelative -> {
                updateApp()
            }
            R.id.cancellationText -> {
                ACacheUtil().clear()
                val intent = Intent(activity, LoginActivity::class.java)
                activity.startActivity(intent)
            }
        }
    }


    private var updateAppInfo: UpdateAppInfo? = null

    private fun checkApp(vNumber: String) {
        Log.e("vNumber", vNumber)
        HttpServer(this).checkApp(vNumber, "Android", mainActivity!!)
    }

    override fun toMainActivity(what: Int, data: Any) {
        when (what) {
            26 -> {
                updateAppInfo = data as UpdateAppInfo
                if (updateAppInfo?.state == 1) {
                    activity.versionUpdateImg.visibility = View.VISIBLE
                }
            }
        }
    }


    private fun updateApp() {
        //版本更新
        //获取当前app的版本号
        Log.e("VersionCode", PackageInfoUtil.getVersionCode(activity).toString())

        if (updateAppInfo!!.state == 1) {
            val mDialog: AlertDialog.Builder = AlertDialog.Builder(activity)
            mDialog.setTitle(BaseApiRetrofit.APK_NAME + "又更新咯！")
            mDialog.setPositiveButton("立即更新") { _, _ ->

                if (Build.VERSION.SDK_INT >= 26) {
                    updataDialog()
                } else {
                    val intent = Intent(activity, UpdateAppService::class.java)
                    activity.startService(intent)
                }
            }?.setNegativeButton("暂不更新") { dialog, which -> dialog.dismiss() }?.setCancelable(false)?.create()?.show()
        } else {
            ToastUtil.toast(activity, "暂时没有检测到新版本")
        }
    }


    private fun updataDialog() {
        val dialogUtil = DialogUtil(mainActivity!!, R.layout.dialog_update_layout, false, 0, 0, 0)
        val updateProgressBarTV: TextView = dialogUtil.view!!.findViewById(R.id.updateProgressBarTV)
        val updateProgressBar: ProgressBar = dialogUtil.view!!.findViewById(R.id.updateProgressBar)



        BaseApiRetrofit().myOkHttp.download()
                .url(BaseApiRetrofit.DownLoadApp)
                .filePath(mainActivity!!.myApplication?.apkSavePath + "/追溯2.0.apk")
                .tag(mainActivity!!)
                .enqueue(object : DownloadResponseHandler() {
                    override fun onFinish(downloadFile: File) {
                        ToastUtil.toast(mainActivity!!, "下载完成")
                        UpdateUtils(mainActivity!!, mainActivity!!.myApplication).showSelectAPK()
                        dialogUtil.dialogDismiss()
                    }

                    @SuppressLint("SetTextI18n")
                    override fun onProgress(currentBytes: Long, totalBytes: Long) {
                        //更新进度条
                        val currentNum = (100 * currentBytes / totalBytes).toInt()
                        updateProgressBarTV.text = currentNum.toString() + "%"
                        updateProgressBar.progress = currentNum
                    }

                    override fun onFailure(error_msg: String) {
                        ToastUtil.toast(mainActivity!!, "下载失败")
                    }
                })


    }

}
